<template>
  <div class="notice_box" v-loading="loading">
    <div class="notice_addbtn">
      <el-button icon="plus" @click="openAddDialog()" type="primary">
        新增公告
      </el-button>
    </div>
    <el-table
      :data="noticeDatas"
      border
      :header-row-style="{ color: '#232324', fontWeight: 'bold' }"
    >
      <el-table-column type="expand">
        <template #default="props">
          <v-md-preview
            :text="props.row.content"
            style="width: 60%; margin-left: 10%"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        type="index"
        :index="indexMethod"
        label="序号"
        width="80"
      />
      <el-table-column
        align="center"
        label="标题"
        min-width="120"
        prop="title"
      />
      <el-table-column
        align="center"
        label="内容"
        show-overflow-tooltip
        min-width="220"
        prop="content"
      />
      <el-table-column
        align="center"
        label="发布人"
        min-width="120"
        prop="author"
      />
      <el-table-column align="center" label="类型" min-width="120" prop="type">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 1" type="success">所有人</el-tag>
          <el-tag v-else-if="scope.row.type === 2">老师</el-tag>
          <el-tag v-else type="warning">学生</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="状态"
        min-width="120"
        prop="isActive"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.isActive" type="success">发布中</el-tag>
          <el-tag v-else type="danger">下架中</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="发布时间"
        min-width="180"
        prop="publishTime"
      />
      <el-table-column
        align="center"
        label="创建时间"
        min-width="180"
        prop="createTime"
      />
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button
            type="primary"
            link
            icon="edit"
            @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            width="180"
            title="是否删除该公告?"
            @confirm="deleteNoticeById(scope.row.noticeId)"
          >
            <template #reference>
              <el-button type="primary" link icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 12px"
      v-model:current-page="noticePageParmas.pageNum"
      v-model:page-size="noticePageParmas.pageSize"
      :page-sizes="[10, 20, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      style="min-width: 900px"
    >
      <el-form
        v-if="dialogFormVisible"
        ref="noticeForms"
        :inline="true"
        :model="noticeForm"
        :rules="rules"
        label-position="top"
        label-width="85px"
      >
        <el-form-item label="标题" prop="title" style="width: 40%">
          <el-input v-model="noticeForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="发布人" prop="author" style="width: 40%">
          <el-input v-model="noticeForm.author" placeholder="请输入发布人" />
        </el-form-item>
        <el-form-item label="类型" prop="type" style="width: 40%">
          <el-select v-model="noticeForm.type" clearable placeholder="Select">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isActive" style="width: 40%">
          <el-switch
            v-model="noticeForm.isActive"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            inline-prompt
            active-text="发布中"
            inactive-text="下架中"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content" style="width: 100%">
          <v-md-editor
            v-model="noticeForm.content"
            height="460px"
            placeholder="请输入内容"
            :disabled-menus="[]"
            @upload-image="handleUploadImage"
          ></v-md-editor>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="formConfirm(noticeForms)">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import {
  reqAddNotice,
  reqDeleteNoticeById,
  reqGetNoticePage,
  reqUpdateNotice,
} from '@/api/publish'
import {
  BasePageQuery,
  NoticePageRes,
  NoticeParams,
  NoticeType,
} from '@/api/publish/type'
import axios from 'axios'
import { Upload_API } from '@/api/upload'
import { GET_TOKEN } from '@/utils/token'

onMounted(async () => {
  await getNoticeInfoPage()
})

const dialogFormVisible = ref<boolean>(false)
const noticePageParmas: BasePageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
})
const noticeDatas = ref<NoticeType[]>()
const total = ref(0)
const loading = ref(false)

const noticeForms = ref<FormInstance>()
let noticeForm: NoticeParams = reactive({
  noticeId: 0,
  title: '',
  content: '',
  author: '',
  type: 1,
  isActive: true,
})

const options = [
  {
    value: 1,
    label: '所有人',
  },
  {
    value: 2,
    label: '老师',
  },
  {
    value: 3,
    label: '学生',
  },
]

const rules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  author: [{ required: true, message: '请输入发布人 ', trigger: 'blur' }],
  type: [{ required: true, message: '请输入接受人类型', trigger: 'blur' }],
  isActive: [{ required: true, message: '请输入是否有效', trigger: 'blur' }],
})

// 添加菜单方法，id为 0则为添加根菜单
const dialogTitle = ref('新增公告')
const isEdit = ref(false)

const getNoticeInfoPage = async () => {
  loading.value = true
  try {
    const { data } = await reqGetNoticePage(noticePageParmas)
    noticeDatas.value = data.list
    total.value = data.total
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

const indexMethod = (index: number) => {
  return index + (noticePageParmas.pageNum - 1) * noticePageParmas.pageSize + 1
}

const deleteNoticeById = async (id: number) => {
  try {
    const { message } = await reqDeleteNoticeById(id)
    ElMessage.success(message)
    await getNoticeInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const addNotice = async () => {
  try {
    const { message } = await reqAddNotice(noticeForm)
    ElMessage.success(message)
    noticeForm = {
      noticeId: 0,
      title: '',
      content: '',
      author: '',
      type: 1,
      isActive: true,
    }
    await getNoticeInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const updateNotice = async () => {
  try {
    const { message } = await reqUpdateNotice(noticeForm)
    ElMessage.success(message)
    await getNoticeInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const formConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        updateNotice()
      } else {
        addNotice()
      }
      dialogFormVisible.value = false
    }
  })
}

const handleUploadImage = (event: Event, insertImage: any, files: File[]) => {
  for (let i in files) {
    const formData = new FormData()
    formData.append('file', files[i])
    axios
      .post(`${Upload_API.IMAGE_URL}`, formData, {
        headers: {
          Authorization: GET_TOKEN() as string,
        },
      })
      .then(
        (response) => {
          const { data } = response.data
          insertImage({
            url: data.imageUrl,
            desc: 'desc',
          })
        },
        (error) => {
          ElMessage.error(error.message)
        },
      )
  }
}

const openAddDialog = () => {
  isEdit.value = false
  if (noticeForm.noticeId !== 0) {
    noticeForm = {
      noticeId: 0,
      title: '',
      content: '',
      author: '',
      type: 1,
      isActive: true,
    }
  }
  dialogTitle.value = '新增公告'
  dialogFormVisible.value = true
}
// 修改菜单方法
const openEditDialog = async (data: NoticeType) => {
  isEdit.value = true
  dialogTitle.value = '编辑公告'
  noticeForm.noticeId = data.noticeId
  noticeForm.title = data.title
  noticeForm.content = data.content
  noticeForm.author = data.author
  noticeForm.type = data.type
  noticeForm.isActive = data.isActive
  dialogFormVisible.value = true
}

const handleSizeChange = (val: number) => {
  getNoticeInfoPage()
}
const handleCurrentChange = (val: number) => {
  getNoticeInfoPage()
}
</script>
<style scoped lang="scss">
.notice_box {
  padding: 24px;

  .notice_addbtn {
    margin-bottom: 12px;
    display: flex;
  }
}
</style>
